package com.nine.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import com.nine.constant.RoomConstant;
import com.nine.entity.Content;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
//@Service
public class TaskService {

    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 模拟进入直播间时的数据
     */
    @PostConstruct
    public void init() {
        log.info("项目启动，直播间初始化，init....");
        System.out.println();

        // 1. 启动一个线程，模拟直播间观众发言
        new Thread(() -> {
            AtomicInteger atomicInteger = new AtomicInteger();
            while (true) {
                // 2. 模拟观众发言，5s一批数据，自己模拟造数据，到100后 break
                if (atomicInteger.getAndIncrement() == 100) {
                    break;
                }
                // 3. 模拟直播100房间号的弹幕数据，拼接redis key， room:100
                String key = RoomConstant.ROOM_KEY + "100";
                Random random = new Random();
                for (int i = 1; i <= 5; i++) {
                    Content content = new Content();
                    content.setId(IdUtil.getSnowflake(1, 1).nextId());

                    int id = random.nextInt(1000) + 1;
                    content.setUserId(id);

                    int temp = random.nextInt(100) + 1;
                    content.setContent("发表言论：" + temp + "\t" + RandomUtil.randomString(temp));

                    long time = System.currentTimeMillis() / 1000;
                    // 4. 将弹幕数据存入redis，原生命令：zadd room:100 time content
                    // ZADD key score1 member1 [score2 member2] ...
                    // redisTemplate操作Zset的API：Boolean add(K key, V value, double score)
                    redisTemplate.opsForZSet().add(key, content, time);

                    log.info("模拟直播间100房间号的发言弹幕数据，用户" + id + "说：" + temp);
                }

                // TODO 在分布式系统中，建议使用 xxl-job 来实现定时，此处简单模拟
                try {
                    TimeUnit.SECONDS.sleep(5);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

                // 模拟观众发言，5s一批数据，自己模拟造数据，到100后 break
                atomicInteger.getAndIncrement();

                log.info("--------------------------每隔5s，拉取一次最新数据---------------------------------------------");
            }
        }, "init_Live_Data").start();


    }

}
